package leetcode_周赛._2022._202207;

import java.util.*;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/7/24 12:14
 * 303 场周赛
 * AC2
 */
public class _24 {

    /**
     * 6126. 设计食物评分系统
     * 算法：设计 + treeMap
     */
    class FoodRatings {
        class FoodRating {
            String name;
            int rating;

            public FoodRating(String name, int rating) {
                this.name = name;
                this.rating = rating;
            }

        }

        Map<String, String> fcMap;
        Map<String, TreeSet<FoodRating>> cfrMap;
        // 为了让 treeSet 可以删除 foodRating
        Map<String, FoodRating> frIndex;

        public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
            int len = foods.length;
            fcMap = new HashMap<>(len);
            cfrMap = new HashMap<>(len);
            frIndex = new HashMap<>(len);
            for (int i = 0; i < len; i++) {
                fcMap.put(foods[i], cuisines[i]);
                FoodRating fr = new FoodRating(foods[i], ratings[i]);
                TreeSet<FoodRating> ts = cfrMap.getOrDefault(cuisines[i],
                        new TreeSet<>((a, b) -> {
                            if (a.rating != b.rating) return b.rating - a.rating;
                            return a.name.compareTo(b.name);
                        }));
                ts.add(fr);
                cfrMap.put(cuisines[i], ts);
                frIndex.put(foods[i], fr);
            }
        }

        public void changeRating(String food, int newRating) {
            String cuisine = fcMap.get(food);
            TreeSet<FoodRating> ts = cfrMap.get(cuisine);
            ts.remove(frIndex.get(food));
            FoodRating fr = new FoodRating(food, newRating);
            ts.add(fr);
            cfrMap.put(cuisine, ts);
            frIndex.put(food, fr);
        }

        public String highestRated(String cuisine) {
            TreeSet<FoodRating> foodRatings = cfrMap.get(cuisine);
            return foodRatings.first().name;
        }

    }

}
